import os
import json

_g_bilibili_cookies = None

def get_bilibili_cookies() -> dict[str, str]:
    global _g_bilibili_cookies
    if _g_bilibili_cookies is None:
        bili_cookie_path = os.path.expanduser('~/.bilibili-cookies.json')
        if os.path.exists(bili_cookie_path):
            with open(bili_cookie_path, 'r') as f:
                cookies = json.load(f)
            if isinstance(_g_bilibili_cookies, list):
                _g_bilibili_cookies = {item['name']: item['value'] for item in cookies}
            else:
                _g_bilibili_cookies = {}
        else:
            _g_bilibili_cookies = {}
    return _g_bilibili_cookies

def get_headers(referer: str | None = None) -> dict[str, str]:
    headers = {
        'Accept': '*/*',
        'Accept-Language': 'en-US,en;q=0.5',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36',
    }
    if referer:
        headers['Referer'] = referer
    return headers

def get_bilibili_params() -> dict:
    return dict(cookies=get_bilibili_cookies(), headers=get_headers())
